/*
 * @(#)MaintEmainArchiveRuleAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.dms.web;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.mandarax.kernel.Fact;
import org.mandarax.kernel.Function;
import org.mandarax.kernel.Predicate;
import org.mandarax.kernel.Prerequisite;
import org.mandarax.kernel.SimplePredicate;
import org.mandarax.util.LogicFactorySupport;

import com.dcivision.dms.bean.EmailMessageToRule;
import com.dcivision.dms.dao.EmailArichivePrivateRuleDAObject;
import com.dcivision.dms.dao.EmailArichiveRuleDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.rules.action.NotifyEmailArchiveAction;
import com.dcivision.rules.action.RuleActionSetAction;
import com.dcivision.rules.action.SaveEmailToDMSAction;
import com.dcivision.rules.action.TriggerWorkflowAction;
import com.dcivision.rules.bean.RuleBaseObject;
import com.dcivision.rules.core.RuleManager;
import com.dcivision.rules.core.RuleMemberFactory;
import com.dcivision.rules.dao.RuleBaseObjectDAObject;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.core.SystemWorkflowConstant;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;


/**
 * <p> Class Name: MaintEmainArchiveRuleAction</p>
 * <p> Decription: This class is for edit and new rule.</p>
 * 
 * 
 * @author        nancy zhang
 * @company       DCIVision Limited
 * @creation date 27/07/2003
 * @version       $Revision: 1.52.4.1 $
 */

public class MaintEmailArchiveRuleAction extends AbstractMaintAction{
  public static final String REVISION = "$Revision: 1.52.4.1 $";
  protected Log log = LogFactory.getLog(this.getClass().getName());
  private String majorDAOClassName = "com.dcivision.dms.dao.EmailArichiveRuleDAObject";
  private boolean isRefresh = false;

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return (SystemFunctionConstant.DMS_PUBLIC_RULE_SETUP);
  }

  /** Creates a new instance of MaintWorkflowRecordAction */
  public MaintEmailArchiveRuleAction () {
    super ();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return this.majorDAOClassName;
  }
   

  public ActionForward execute(ActionMapping mapping , ActionForm form ,
      HttpServletRequest request , HttpServletResponse response)
      throws ServletException {

    //========================================
    //init the function code and DAO
    initFunctionCodeAndDAO(form, request);
    //========================================
    
    MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form;     
    //get all general workflow
    this.getAllGeneralWorkflow(form ,request);
    
    
    if ( !Utility.isEmpty(ruleForm.getOpMode())  ) {
      //add string[] to ruleform
    	this.getFormData(form, request);
    	if ((GlobalConstant.OP_MODE_REFRESH).equals (ruleForm.getOpMode ( ))) {
    		isRefresh = true;
        ruleForm.setOpMode ("");
    	}	else {
    	  ruleForm.setAddFlag(null);	
    	}
    } else {
    	isRefresh = false;
    }
    
    //get the rule list
    this.getRuleList(ruleForm, request, false);


    if (!Utility.isEmpty (ruleForm.getDelType ( )) && ruleForm.getDelType ( ).equals ("Criterion")) {
      //get ruleForm.getDelID() and delete from criterion list.
      List tempList = ruleForm.getCondition ( );
      tempList.remove ((ruleForm.getDelID ( )).intValue ( ));
      ruleForm.setCondition (tempList);
          
      ruleForm.setCriterionNum (ruleForm.getCriterionNum ( ) - 1);
      ruleForm.setDelID (null);
      ruleForm.setDelType (null);
    } else if (!Utility.isEmpty (ruleForm.getDelType ( )) && ruleForm.getDelType ( ).equals ("Action")) {
      //get ruleForm.getDelID() and delete from action list.
      List tempList = ruleForm.getConclusion( );
      tempList.remove ((ruleForm.getDelID ( )).intValue ( ));
      ruleForm.setConclusion (tempList);
          
      ruleForm.setActionNum (ruleForm.getActionNum ( ) - 1);
      ruleForm.setDelID (null);
      ruleForm.setDelType (null);
    }
    
    String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.RULES_KB_FILE_PATH);
    File kbFile = new File(path);
    if(!kbFile.exists()){
      kbFile.mkdir();
    }
         
    return super.execute (mapping, form, request, response);

  }
  
  /**
   * get the all general workflow
   * @param form the action form
   * @param request http servlet request
   * @throws ApplicationException
   */
  private void getAllGeneralWorkflow(ActionForm form ,HttpServletRequest request) throws ApplicationException{
    MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form;
    List allWorkflowList = new ArrayList();
    WorkflowRecordDAObject wfRecordDAO = new WorkflowRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
    
    //get general workflow.
    allWorkflowList = wfRecordDAO.getLastBySysWorkflowCategoryID(new Integer(SystemWorkflowConstant.SYS_GENERAL_WORKFLOW));    
    
    List flowByFormList = wfRecordDAO.getLastBySysWorkflowCategoryID(new Integer(SystemWorkflowConstant.FMB_SUBMISSION_BY_FORM));
    //List flowByFormGroupList = wfRecordDAO.getLastBySysWorkflowCategoryID(new Integer(SystemWorkflowConstant.FMB_SUBMISSION_BY_GROUP));
    
    List allWorkflowListFinal = new ArrayList();
    for (int i=0; i<allWorkflowList.size(); i++){
      WorkflowRecord wfRecord = (WorkflowRecord)allWorkflowList.get(i);
      if (!Utility.isEmpty(wfRecord.getEndDate())){
        //Timestamp currentTime = Utility.getCurrentTimestamp();
        long currentTime = TextUtility.parseLong(TextUtility.formatTimestampToIndex(Utility.getCurrentTimestamp()));
        long endTime = TextUtility.parseLong(TextUtility.formatTimestampToIndex(wfRecord.getEndDate()));
        if (currentTime < endTime){
          allWorkflowListFinal.add(wfRecord);
        }
      }else{
        allWorkflowListFinal.add(wfRecord);
      }
    }
    if (!Utility.isEmpty(flowByFormList)) {
      allWorkflowList.addAll(flowByFormList);
    }
    
   
    
    ruleForm.setAllWorkflow(allWorkflowListFinal);
    
    flowByFormList = null;
    allWorkflowList = null;
    wfRecordDAO = null;    
  }

  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	this.handlePrerequisiteActionFact(form, request);
  	super.insertRecord(mapping, form, request, response);
  	
    MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form;  
    this.getRuleList(ruleForm, request, true);
    this.init(mapping,form,request,response);
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	this.handlePrerequisiteActionFact(form, request);
  	super.updateRecord(mapping, form, request, response);
  }

  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.deleteRecord(mapping, form, request, response);
  }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    AbstractDAObject dao = this.getMajorDAObject(request);
    AbstractBaseObject bean = dao.getObjectByID(TextUtility.parseIntegerObj(form.getID()));      
    
    form.setFormData(bean);    
  }
  
  public void init(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form;   
  	
  	if ( !isRefresh ) {  		
  		String[] crierion = new String[3];
  		List criList = new ArrayList ( );
  		criList.add (crierion);      
  		ruleForm.setCondition(criList);
  		
  		String[] action = new String[2];
  		List atnList = new ArrayList ( );
  		atnList.add (action);
  		ruleForm.setConclusion(atnList);
  	}
  }
  
  /**
   * init the function code and DAO
   * @param form         the action form
   * @param request      the http serverlet request
   */
  private void initFunctionCodeAndDAO (ActionForm form, HttpServletRequest request){
  	MaintEmailArchiveRuleForm ruleForm =(MaintEmailArchiveRuleForm)form;
    //List Private Rule 
  	log.debug("============================"+ruleForm.getRuleType());
  	if(RuleOperationConstant.PRIVATE_RULE_FUNCTION.equals(ruleForm.getRuleType())){
  		request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY, null);
  		this.setFunctionCode(SystemFunctionConstant.DMS_PRIVATE_RULE_SETUP);
  		request.setAttribute(GlobalConstant.DAO_KEY, null);
  		this.majorDAOClassName = "com.dcivision.dms.dao.EmailArichivePrivateRuleDAObject";
  	
    //List Public Rule		
  	} else {
  		request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY, null);
  		this.setFunctionCode(SystemFunctionConstant.DMS_PUBLIC_RULE_SETUP);  		
  		request.setAttribute(GlobalConstant.DAO_KEY, null);
  		this.majorDAOClassName = "com.dcivision.dms.dao.EmailArichiveRuleDAObject";
  	}	
  	log.debug("Faction Code: " + this.getFunctionCode());
  	log.debug("Marjor DAO Class Name: "+ this.getMajorDAOClassName() );
  }
  
  /**
   * get the Prerequisite List 
   * @param form     the action form
   * @param request  the http servlet request
   * @return list
   * @throws ApplicationException
   */
  private List getPrerequisiteList(ActionForm form, HttpServletRequest request) throws ApplicationException {
  	MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm)form;
  	RuleMemberFactory factory = new RuleMemberFactory();
		
  	RuleManager ruleManager = new RuleManager(this.getSessionContainer(request), this.getConnection(request));
  	LogicFactorySupport lfs = new LogicFactorySupport();  	
  	
  	List prerequisiteList = new ArrayList();  	
  	
  	if(!Utility.isEmpty(ruleForm.getCondition())){
  	  for(int i = 0;i < ruleForm.getCondition().size(); i++){
  	    String[] strArr = (String[])ruleForm.getCondition().get(i);
  	    log.debug("Condition is :" + strArr[0] + ":" + strArr[1] + ":" + strArr[2]);

  	    Prerequisite prereq = null;
  	    Function function = ruleManager.createFunction(strArr[0] ,EmailMessageToRule.class);
  	    if ( function.getReturnType().equals( Integer.class) ) {
  	      prereq = lfs.prereq(
  	          factory.getPredicate( strArr[1] ), 
  	          lfs.cplx(ruleManager.createFunction(strArr[0] ,EmailMessageToRule.class), "Email Message"),			
  	          Integer.valueOf(strArr[2])
  	      );
  	    } else {  			
  	      prereq = lfs.prereq(
  	          factory.getPredicate( strArr[1] ), 
  	          lfs.cplx(ruleManager.createFunction(strArr[0] ,EmailMessageToRule.class), "Email Message"),			
  	          strArr[2]
  	      );
  	    }  		
  	    prereq.setProperty("PredicateName",strArr[1]);	
  	    
  	    log.debug("Prerequisite Container: " + prereq.getContainer() );
  	    prerequisiteList.add(prereq);
  	  }
    }
  	log.debug("get Perrequisite List: " + prerequisiteList.size());
  	return prerequisiteList;  	
  }
  
  /**
   * get action Fact
   * @param form     the action form
   * @param request  the http servlet request
   * @return Fact
   * @throws ApplicationException
   */
  private Fact getActionFact(ActionForm form, HttpServletRequest request) throws ApplicationException {
  	MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm)form;
  	LogicFactorySupport lfs = new LogicFactorySupport();  	
  	
  	List actionList = new ArrayList();  	
  	for(int i = 0; i < ruleForm.getConclusion().size(); i++){
  		
  		String[] strArr = (String[])ruleForm.getConclusion().get(i);
      String ruleName = ruleForm.getRuleName();
  		log.debug("Conclusion is :" + strArr[0] + ":" + strArr[1]);
  		//String actionMap = request.getParameter("actionMap" + i);  	
  		
  		log.debug("Action " + i + " is " + strArr[0] );
  		log.debug("Parameter " + i + " is " + strArr[1] );
  		
  		//Start Workflow
  		if( MaintEmailArchiveRuleForm.ACTION_START_WORKFLOW.equals( strArr[0]) ){
  			TriggerWorkflowAction triggerAction = new TriggerWorkflowAction();
  			triggerAction.setTarget( strArr[1] );
        triggerAction.setRuleName(ruleName);
  			actionList.add(triggerAction);
  			
  		
  		//Notify me
  		} else if ( MaintEmailArchiveRuleForm.ACTION_NOTIFY_ME.equals(strArr[0]) ){
  			NotifyEmailArchiveAction notifyAction = new NotifyEmailArchiveAction();
  			notifyAction.setTarget( strArr[1] );
        notifyAction.setRuleName(ruleName);
        notifyAction.setRuleDescription(ruleForm.getDetailDescription());
  			actionList.add(notifyAction);
  			
  		//Route to DMS	
  		} else if ( MaintEmailArchiveRuleForm.ACTION_RUTE_TO.equals(strArr[0]) ){
  			SaveEmailToDMSAction fileToDMSAction = new SaveEmailToDMSAction();
  			fileToDMSAction.setTarget( strArr[1] );
        fileToDMSAction.setRuleName(ruleName);
  			actionList.add(fileToDMSAction);
  		}			  
  	}
  	
  	RuleActionSetAction actionSet = new RuleActionSetAction(actionList);
  	Predicate actionSetPred = new SimplePredicate(RuleOperationConstant.SIMPLE_PREDICATE_NAME, new Class[]{RuleActionSetAction.class, EmailMessageToRule.class});
		Fact actionFact = lfs.fact(actionSetPred, actionSet, "Email Message");
		log.debug("get Action Fact." + actionFact.getContainer());
		return actionFact;
  }

  
  /**
   * handle the Prerequisite & ActionFact
   * @param form    the Abstract Action Form
   * @param request the Http Servlet Request
   * @throws ApplicationException
   */
  private void handlePrerequisiteActionFact(AbstractActionForm form, HttpServletRequest request) throws ApplicationException {
  	MaintEmailArchiveRuleForm ruleForm =(MaintEmailArchiveRuleForm)form;  	
  	
  	RuleBaseObject ruleObj = ( RuleBaseObject )ruleForm.getFormData();
  	//get the condition list
  	ruleForm.setPrerequisiteList(this.getPrerequisiteList( form, request));
  	  	
  	//get the Action Fact
  	ruleForm.setActionFact(this.getActionFact(form, request));	
  }
  
  /**
   * get the form data
   * @param form
   * @param request
 * @throws ApplicationException 
   */
  private void getFormData_1( ActionForm form, HttpServletRequest request) throws ApplicationException{
  	MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form;  
  	List criList = new ArrayList ( );
  	String[] tempString = null;
  	
    tempString=new String[ruleForm.getCriterionNum ()];
    int l=0;
    for (int i = 0; i < ruleForm.getCriterionNum ( ); i++ ) {
      String[] crierion = new String[3];
      crierion[0] = request.getParameter ("crierionMap" + i);
      if(MaintEmailArchiveRuleForm.CRITERION_RECEIPIENT.equals(crierion[0])||MaintEmailArchiveRuleForm.CRITERION_EMAILTO.equals(crierion[0])||MaintEmailArchiveRuleForm.CRITERION_EMAILCC.equals(crierion[0])||MaintEmailArchiveRuleForm.CRITERION_EMAILFROM.equals(crierion[0])){
        crierion[1] = request.getParameter ("CRITERION_type" + i);
      }else if(MaintEmailArchiveRuleForm.CRITERION_MESSAGE.equals(crierion[0])){
        crierion[1] = request.getParameter ("CRITERION_type3" + i);
      }else{
        crierion[1] = request.getParameter ("CRITERION_type2" + i);
      }
      if(MaintEmailArchiveRuleForm.CRITERION_RECEIPIENT.equals(crierion[0])){
        if (Utility.isEmpty (ruleForm.getDelType())||(!Utility.isEmpty (ruleForm.getDelID())&&!ruleForm.getDelID().equals(new Integer(i)))) {
          if(Utility.isEmpty(request.getParameter ("allUsers_" + i))){
            crierion[2]="";
            tempString[l]="";
          }else{
            crierion[2]=request.getParameter ("allUsers_" + i);
            tempString[l]=request.getParameter ("allUsers_" + i);
          }
          l=l+1;
        }
      }else if(MaintEmailArchiveRuleForm.CRITERION_SUBJECT.equals(crierion[0])){
        crierion[2] = request.getParameter ("criterionT" + i);
        tempString[l]="";
        l=l+1;
      }else if(MaintEmailArchiveRuleForm.CRITERION_MESSAGE.equals(crierion[0])){
        crierion[2] = request.getParameter ("criterionS" + i);
        tempString[l]="";
        l=l+1; 
      }else if(MaintEmailArchiveRuleForm.CRITERION_EMAILTO.equals(crierion[0])||MaintEmailArchiveRuleForm.CRITERION_EMAILCC.equals(crierion[0])||MaintEmailArchiveRuleForm.CRITERION_EMAILFROM.equals(crierion[0])){
        String showValue = request.getParameter ("criterionShowValue" + i);
        String hiddenValue = request.getParameter ("criterionHiddenValue" + i);
        String pageValue = request.getParameter ("dummy_selectUsers_" + i);
        String value ="";
        showValue = TextUtility.replaceString(showValue,RuleOperationConstant.SPLIT_COMMA,RuleOperationConstant.SPLIT_SEMICOLON);
        pageValue = TextUtility.replaceString(pageValue,RuleOperationConstant.SPLIT_COMMA,RuleOperationConstant.SPLIT_SEMICOLON);
        String[] hiddenValueAry = TextUtility.splitString(hiddenValue, RuleOperationConstant.SPLIT_COMMA);
        String[] showValueAry;
        String[] pageValueAry;
        String subtractValue ="";
        
        if (!Utility.isEmpty(pageValue)){
          if(!showValue.equals(pageValue)){
            showValueAry = TextUtility.splitString(showValue, RuleOperationConstant.SPLIT_SEMICOLON);
            pageValueAry = TextUtility.splitString(pageValue, RuleOperationConstant.SPLIT_SEMICOLON);
            if (Utility.isEmpty(showValueAry)){
              //value = TextUtility.replaceString(value,RuleOperationConstant.SPLIT_COMMA,RuleOperationConstant.SPLIT_SEMICOLON);
              value = pageValue;
            }else{
              if (!Utility.isEmpty(showValueAry)&&!Utility.isEmpty(pageValueAry)){
                value = this.compareArray(pageValueAry,showValueAry);
                subtractValue = this.compareArray(showValueAry,pageValueAry);
              }
            }
            
            
            if (!Utility.isEmpty(hiddenValueAry)){
              hiddenValue = "";
              int hiddenCount = 0;
              for (int k =0; k<hiddenValueAry.length; k++){
                String splitStr = hiddenValueAry[k];
                if (splitStr.indexOf(RuleOperationConstant.SPLIT_COLON)>-1){
                  if (hiddenCount!=0){
                    hiddenValue += RuleOperationConstant.SPLIT_COMMA;
                  }
//                  if (!Utility.isEmpty(subtractValue)){ 
//                    String[] subtractValueAry = TextUtility.splitString(subtractValue, RuleOperationConstant.SPLIT_COMMA);
//                    for (int m=0; m<subtractValueAry.length; m++){
//                      boolean hiddenFlag = true;
//                      String subtractStr = subtractValueAry[m];
//                      
//                    }
//                    hiddenValue += splitStr;
//                    hiddenCount ++;
//                  }else{
                    hiddenValue += splitStr;
                    hiddenCount ++;
//                  }
                }
              }
            }
            
            
          }
        }
        
        
        
        
        if (Utility.isEmpty(value)){
          crierion[2] = hiddenValue;            
        }else{
          crierion[2] = value + RuleOperationConstant.SPLIT_COMMA + hiddenValue;            
        }
        
        tempString[l]="";
        l=l+1;
      }else{
        crierion[2] = request.getParameter ("criterionT" + i);
        tempString[l]="";
        l=l+1;
      }
      criList.add (crierion);
      crierion = null;
    }
    ruleForm.setAllUsers(tempString);
    ruleForm.setCondition(criList);
    tempString = null;
    criList = null;

    List atnList = new ArrayList ( );
    int k = 0;
    String[] actionTempString = new String[ruleForm.getActionNum()];
    for (int i = 0; i < ruleForm.getActionNum ( ); i++ ) {
      String[] action = new String[2];
      action[0] = request.getParameter ("actionMap" + i);
      if(MaintEmailArchiveRuleForm.ACTION_RUTE_TO.equals(action[0])){
        if(Utility.isEmpty(request.getParameter ("locationPath_" + i))){
          action[1] = "";
          actionTempString [k]= "";            
        }else{
          //action[1] = (String)request.getParameter ("locationPath_" + i);
          //actionTempString [k]= rootIDTep + RuleOperationConstant.SPLIT_STRING + parentIDTep;
          actionTempString [k]= request.getParameter ("locationPath_" + i);
          String rootIDTep = request.getParameter ("rootID_" + i);
          String parentIDTep = request.getParameter ("parentID_" + i);
          action[1] = rootIDTep + RuleOperationConstant.SPLIT_STRING + parentIDTep;
        }
        k = k+1;
      }else if(MaintEmailArchiveRuleForm.ACTION_NOTIFY_ME.equals(action[0])){
        String notificationWay ="";
        if(!Utility.isEmpty(request.getParameterValues("actionN" + i))){
          for (int j = 0; j<request.getParameterValues("actionN" + i).length; j++){
            if (j!= 0){          
              notificationWay += RuleOperationConstant.SPLIT_STRING;
            }
            notificationWay += request.getParameterValues("actionN" + i)[j];
          }
        }
        action[1] = notificationWay; 
        actionTempString [k]= ""; 
        k = k+1;
      }else{
        action[1] = request.getParameter ("actionS" + i);
        actionTempString [k]= ""; 
        k = k+1;
      }
      atnList.add (action);
      action = null;  
    }
    ruleForm.setLocationPath(actionTempString);
    ruleForm.setConclusion(atnList);
    actionTempString = null;
    atnList = null;
  }
  
  
  private String compareArray(String[] pageValueAry ,String[] showValueAry){
    String value = "";
    int count = 0;
    
    for (int x=0 ;x<pageValueAry.length; x++){
      String pageStr = pageValueAry[x];
      boolean flag = false;
      for (int y=0 ;y<showValueAry.length; y++){
        String showStr = showValueAry[y];
        if (showStr.equals(pageStr)){
          flag = true;
          showStr = null;
          break;
        }
        showStr = null;
      }
      if (!flag){
        if (count!=0){
          value += RuleOperationConstant.SPLIT_COMMA;
        }
        value += pageStr;
        count ++;
      }
      pageStr = null;
    }
    
    return value;
  }
  
  /**
   * get the rule list
   * @param ruleForm
   * @param request
   * @param afresh
   * @throws ApplicationException
   */
  private void getRuleList(MaintEmailArchiveRuleForm ruleForm , HttpServletRequest request, boolean afresh) throws ApplicationException{
    RuleBaseObjectDAObject ruleBaseObjDAO = null;
    if(RuleOperationConstant.PRIVATE_RULE_FUNCTION.equals(ruleForm.getRuleType())){
      ruleBaseObjDAO = new EmailArichivePrivateRuleDAObject(this.getSessionContainer(request), this.getConnection(request));
    } else {
      ruleBaseObjDAO = new EmailArichiveRuleDAObject(this.getSessionContainer(request), this.getConnection(request));
    }
            
    List ruleList = ruleBaseObjDAO.getFullList();
    	
    String[][] ruleOrderArr = null;    
   	String[] firstItem = new String[]{MessageResourcesFactory.getMessage(this.getLocale(request), "common.options.select_menu.select_one"),"0"};
    	
   	
   	if(!Utility.isEmpty(ruleList)){        
      List tmpList = new ArrayList();
      for(int i=0; i<ruleList.size(); i++){        
        RuleBaseObject ruleObj = (RuleBaseObject)ruleList.get(i); 
        if (GlobalConstant.FALSE.equals(ruleObj.getRuleEnable()) ) {
          continue;
        }
        tmpList.add(ruleObj);
      }      
      
      ruleOrderArr = new String[tmpList.size() + 1][2];
      ruleOrderArr[0] = firstItem;
   		for(int i=0; i<tmpList.size(); i++){
   			String[] ruleListValue = new String[2];
   			RuleBaseObject ruleObj = (RuleBaseObject)tmpList.get(i);    			
   			ruleListValue[1] = ruleObj.getRuleSeqNo();
   			ruleListValue[0] = ruleObj.getRuleName();
   			ruleOrderArr[i + 1] = ruleListValue;
   			ruleListValue = null;
   		}
   } else {
     ruleOrderArr = new String[1][2];
     ruleOrderArr[0] = firstItem;
   }
    	
   request.setAttribute("ruleOrderArray",ruleOrderArr);
   request.getSession().setAttribute("ruleOrderArray",ruleOrderArr);
   firstItem = null;
   ruleOrderArr = null;
   ruleList = null;  
   ruleBaseObjDAO = null;
   
  }
  
  //=================================================
  private void getFormData( ActionForm form, HttpServletRequest request) throws ApplicationException{
    MaintEmailArchiveRuleForm ruleForm = (MaintEmailArchiveRuleForm) form; 
    
    
    String condValue = ruleForm.getConditionValue();
    String actionValue = ruleForm.getActionValue();
    
    log.debug("Condition value: " + condValue +":" + request.getParameter("conditionValue"));    
    log.debug("Action value: " + actionValue);
    
    if (!Utility.isEmpty(condValue)) {    
    	//set the condition
    	String[] condArr = TextUtility.splitString(condValue,"$$");   
    	
    	List condList = new ArrayList();    
    	for (int i = 0; i < condArr.length; i++ ) {    		
    		String[] condition = TextUtility.splitString(condArr[i], "##");
    		log.debug("condition::"+condition[0]+":"+condition[1]+":"+condition[2]);
    		condList.add (condition);      
    	}    
    	ruleForm.setCondition(condList);
    	
    	//set the conclusion
    	String[] actionArr = TextUtility.splitString(actionValue, "$$");    
    	List actionList = new ArrayList();
    	
    	for (int i = 0; i < actionArr.length; i++ ) { 
    		String[] action = TextUtility.splitString(actionArr[i], "##");
    		log.debug("action::"+action[0]+":"+action[1]);
    		actionList.add (action);      
    	}
      if(Utility.isEmpty(ruleForm.getConditionStr())){
    	  ruleForm.setConditionStr(condValue);
      }
      if(Utility.isEmpty(ruleForm.getConclusionStr())){
        ruleForm.setConclusionStr(actionValue);
      }
    	ruleForm.setConclusion(actionList);  
    }
  }
  
  
  
  
  
}
